<?php

namespace app\admin\model\shop\order;

use app\admin\model\Admin;
use app\shop\library\ShopHelper;
use think\Model;
use think\model\relation\BelongsTo;

/**
 * Export
 */
class Export extends Model
{
    // 表名
    protected $name = 'shop_order_export';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    public function admin(): BelongsTo
    {
        return $this->belongsTo(Admin::class, 'admin_id', 'id');
    }

    public static function onBeforeDelete(Model $model): Model
    {
        @unlink(public_path() . $model->getData('export_file_path'));

        return $model;
    }

    public function getTimeRangeAttr(): string
    {
        $where = ShopHelper::json_to_array($this->getData('query_params'))['where'] ?? [];

        foreach ($where as $item) {
            list($field, $op, $val) = $item;
            if (str_contains(strtolower($field), 'create_time')) {
                list($start, $end) = $val;
                $start = $start ? date('Y-m-d H:i:s', $start) : '未指定';
                $end   = $end ? date('Y-m-d H:i:s', $end) : '未指定';

                return sprintf("开始时间: %s\n结束时间: %s", $start, $end);
            }
        }

        return '全部';
    }

    public function getQueryParamsAttr($value): array
    {
        return ShopHelper::json_to_array($value);
    }
}